import { get_broadcast_info, uuid_token } from '@/services/broadcast';
import AgoraRTC from 'agora-rtc-sdk-ng';
import AgoraRTM from 'agora-rtm-sdk';
import { message as M, Modal, Tag } from 'antd';
import { useEffect, useState } from 'react';
import './index.less';
import { random_int } from '@/utils/randomstring';
var background = '';
var RTCclient: any;
var RTMclient: any;
var RTMchannel: any;
const options = {
  appId: '268a993cd77249cf9f3c1e09a279e96c',
};
const Broadcast_share = () => {
  // 获取URL参数
  const getUrlParam = (name: string) => {
    const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
    const r = window.location.search.substr(1).match(reg);
    if (r != null) {
      return decodeURIComponent(r[2]);
    }
    return null;
  };
  // 获取用户id
  const userId: any = random_int(9);
  // 获取直播频道
  const channel: any = getUrlParam('channel');
  console.log('userId', userId, 'channel', channel);
  // 存储直播预告模态框的状态
  const [webStatus, setWebStatus] = useState(false)
  const [appStatus, setAppStatus] = useState(false)
  // 存储直播预告详情
  const [brocastInfo, setBrocastInfo] = useState<any>(undefined)

  useEffect(() => {
    // 获取直播详情
    const getData = async () => {
      if (channel) {
        let res: any = await get_broadcast_info({ channel })
        console.log('res111111111111111111111111111', res);
        if (res.code == 200) {
          setBrocastInfo(res.data)
          if (res.data.status == 0 || res.data.status == 2 || res.data.status == 3) {
            if (
              navigator.userAgent.match(/Mobi/i) ||
              navigator.userAgent.match(/Android/i) ||
              navigator.userAgent.match(/iPhone/i)
            ) {
              // 当前设备是移动设备
              setAppStatus(true)
            } else {
              setWebStatus(true)
            }
          } else {
            join_broadcast();
            // 当前设备是移动设备
            setAppStatus(false)
            setWebStatus(false)
          }
        }
      }
    }
    getData()

  }, [])

  //获取直播信息 获取uuid和channel 加入直播间
  const join_broadcast = async () => {
    let uuid_request_body = {
      user_id: userId,
      origin: 3,
      channel: channel,
    };
    let params: any = await uuid_token(uuid_request_body);
    console.log('params', params);

    if (params.msg == 'ok') {
      RTCclient = AgoraRTC.createClient({ mode: 'live', codec: 'vp8' });
      RTCclient.setClientRole('audience');
      RTCclient.on('user-published', async (user: any, mediaType: any) => {
        // setPublish(true);
        await RTCclient.subscribe(user, mediaType);
        console.log('user-published', user, mediaType);
        if (mediaType === 'video') {
          // 订阅完成后，从 `user` 中获取远端视频轨道对象
          const remoteVideoTrack = user.videoTrack;
          // 动态插入一个 DIV 节点作为播放远端视频轨道的容器
          const playerContainer = document.getElementById('host');
          // 订阅完成，播放远端音视频
          // 传入 DIV 节点，让 SDK 在这个节点下创建相应的播放器播放远端视频
          remoteVideoTrack.play(playerContainer, { mirror: false, fit: 'contain' });
        }

        // 表示本次订阅的是音频
        if (mediaType === 'audio') {
          // 订阅完成后，从 `user` 中获取远端音频轨道对象
          const remoteAudioTrack = user.audioTrack;
          console.log('audio', remoteAudioTrack);
          // 播放音频因为不会有画面，不需要提供 DOM 元素的信息
          remoteAudioTrack.play();
        }
      });
      RTCclient.on('user-unpublished', (user: any, mediaType: string) => {
        console.log('******************* user-unpublished *******************');
        // 远端用户取消发布或离开频道
        if (mediaType === 'video') {
          // 获取刚刚动态创建的 DIV 节点
          const playerContainer: any = document.getElementById('host');
          // 销毁这个节点
          // playerContainer.innerHTML = '';
        }
      });
      RTCclient.join(options.appId, channel, params.data.rtctoken, params.data.uuid);
      join(params.data.uuid, params.data.rtmtoken, channel);
    }
  };

  // 加入RTM频道
  const join = async (uuid: number, rtmtoken: string, channel: string) => {
    console.log(uuid, rtmtoken, channel);
    RTMclient = AgoraRTM.createInstance(options.appId);
    console.log('RTMclient', RTMclient);
    await RTMclient.login({ uid: uuid.toString(), token: rtmtoken });
    RTMchannel = RTMclient.createChannel(channel);
    console.log('Rtm', RTMchannel);
    await RTMchannel.join();
    // 频道消息
    RTMchannel.on('ChannelMessage', async (message: any, memberId: any) => {
      console.log('messsage: ', message, ', memberId: ', memberId);
      get_message(JSON.parse(message.text), memberId);
    });
  };
  const get_message = async (message: any, memberId: number) => {
    if (message.type === 'broadcast_end_%fJ9DG#L') {
      M.info('直播已结束！');
    }
  };
  return (
    <>
      <div id="main" style={{ width: '100%', height: '100%' }}>
        <div id="host" style={{ width: '100%', height: '100%' }}></div>
        {brocastInfo === undefined ? '' : <><Modal title=""
          open={webStatus}
          width={822}
          footer={null}
          closeIcon={null}
        >
          <div style={{ width: '100%', height: '104px', display: 'flex', alignItems: 'center' }}>
            <div style={{ width: '56px', height: '56px', marginRight: "10px" }}><img src={brocastInfo.user_headimg ? brocastInfo.user_headimg : "/head_img.svg"} alt="" style={{ width: '56px', height: '56px', borderRadius: '50%' }} /></div>
            <div style={{ height: '56px', display: 'flex', flexDirection: "column", alignItems: "flex-start", justifyContent: 'space-around' }}>
              <div style={{
                fontFamily: 'PingFang SC, PingFang SC',
                fontWeight: 400,
                fontSize: '16px',
                color: '#333333',
                textTransform: 'none',
              }}>{brocastInfo.user_name}</div>
              <div style={{
                fontFamily: 'PingFang SC, PingFang SC',
                fontWeight: 400,
                fontSize: '14px',
                color: '#7F7F7F',
                textTransform: 'none',
              }}>{brocastInfo.platform_name}</div>
            </div>
          </div>
          <div style={{
            width: '774px', height: '415px', background: '#FFFFFF',
            borderRadius: '18px 18px 18px 18px',
            border: '1px solid rgba(0,98,255,0.2)'
          }}>
            <div style={{ width: '100%', height: '100%' }}>
              <img style={{ width: '100%', height: '100%', borderRadius: '18px 18px 18px 18px', }} src={brocastInfo.icon ? brocastInfo.icon : '/shareIcon.png'} alt="" />
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: "center", marginTop: "18px" }}>
            <div>
              {brocastInfo.status == 0 ? <Tag color="red">
                未开始
              </Tag> : ""}
              {brocastInfo.status == 2 ? <Tag color="green">
                已完成
              </Tag> : ""}
              {brocastInfo.status == 3 ? <Tag color="orange">
                未完成
              </Tag> : ""}
            </div>
            <div style={{
              fontFamily: 'PingFang SC, PingFang SC',
              fontWeight: 'bold',
              fontSize: '24px',
              color: '#333333',
              textTransform: 'none'
            }}>{brocastInfo.name}</div>
          </div>
          <div style={{
            fontFamily: 'PingFang SC, PingFang SC',
            fontWeight: 400,
            fontSize: '20px',
            color: '#7F7F7F',
            marginTop: '10px'
          }}>直播时间：{brocastInfo.start_time}</div>
        </Modal>
          <Modal
            width={335}
            open={appStatus}
            footer={null}
            closeIcon={null}
            centered
          >
            <div style={{ height: '84px', width: '100%', display: 'flex', alignItems: "center" }}>
              <div style={{ width: '44px', height: '44px', marginRight: '10px' }}>
                <img src={brocastInfo.user_headimg ? brocastInfo.user_headimg : "/head_img.svg"} alt="" style={{ width: '100%', height: '100%', borderRadius: '50%' }} />
              </div>
              <div>
                <div style={{
                  fontFamily: 'PingFang SC, PingFang SC',
                  fontWeight: 400,
                  fontSize: '15px',
                  color: '#333333',
                }}>
                  {brocastInfo.user_name}
                </div>
                <div
                  style={{
                    fontFamily: 'PingFang SC, PingFang SC',
                    fontWeight: 400,
                    fontSize: '13px',
                    color: '#7F7F7F',
                  }}>{brocastInfo.platform_name}</div>
              </div>
            </div>
            <div style={{
              width: '100%', height: '187px', background: '#F1F1F1',
              borderRadius: '12px 12px 12px 12px',
              border: '1px solid #B7D2FF'
            }}>
              <div style={{ width: '100%', height: '100%' }}>
                <img style={{ width: '100%', height: '100%', borderRadius: '12px 12px 12px 12px' }} src={brocastInfo.icon ? brocastInfo.icon : '/shareIcon.png'} alt="" />
              </div>
            </div>
            <div style={{ display: 'flex', alignItems: "center", marginTop: "18px" }}>
              <div>
                {brocastInfo.status == 0 ? <Tag color="red">
                  未开始
                </Tag> : ""}
                {brocastInfo.status == 2 ? <Tag color="green">
                  已完成
                </Tag> : ""}
                {brocastInfo.status == 3 ? <Tag color="orange">
                  未完成
                </Tag> : ""}
              </div>
              <div style={{
                fontFamily: 'PingFang SC, PingFang SC',
                fontWeight: 'bold',
                fontSize: '16px',
                color: '#333333',
                textTransform: 'none'
              }}>{brocastInfo.name}</div>
            </div>
            <div style={{
              fontFamily: 'PingFang SC, PingFang SC',
              fontWeight: 400,
              fontSize: '13px',
              color: '#7F7F7F',
              marginTop: '10px'
            }}>直播时间：{brocastInfo.start_time}</div>
          </Modal></>}

      </div>
    </>
  );
};
export default Broadcast_share;
